<template>

    <el-button plain @click="dialogVisible = true" style="margin-bottom: 20px;">
        上传用例
    </el-button>

    <el-dialog v-model="dialogVisible" title="上传用例" width="500" :before-close="handleClose" destroy-on-close>

        <el-form ref="formRef" style="max-width: 600px" :model="numberValidateForm" label-width="auto"
            class="demo-ruleForm">
            <el-form-item label="用例名称" prop="case_name" :rules="[
                { required: true, message: '用例名称是必填项' },
            ]">
                <el-input v-model="case_name" type="text" autocomplete="off" />
            </el-form-item>

            <el-form-item label="所属模块" prop="functional" :rules="[
                { required: true, message: '所属模块是必填项' },
            ]">
                <el-select v-model="functional" placeholder="请选择所属模块" size="large" style="width: 600px">
                    <el-option v-for="item in functional_options" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
        </el-form>

        <el-upload ref="uploadRef" class="upload-demo" :auto-upload="false" :before-upload="checkFile"
            :on-change="handleFileChange">
            <template #trigger>
                <el-button type="primary" style="margin-right: 20px;">选择文件</el-button>
            </template>

            <el-button class="ml-3" type="success" @click="submitUpload">
                上传到服务器
            </el-button>

            <template #tip>
                <div class="el-upload__tip">
                    只能上传 .xlsx 文件，文件大小需小于 500kb
                </div>
            </template>
        </el-upload>
    </el-dialog>

     <el-table :data="tableData" stripe style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }" :cell-style="{ padding: '8px 0' }"
        @row-click="handleRowClick">

        <el-table-column type="selection" width="55" align="center" />

        <el-table-column prop="case_name" label="用例名称" width="180" show-overflow-tooltip>
            <template #default="{ row }">
                <el-tag effect="plain">{{ row.case_name }}</el-tag>
            </template>
        </el-table-column>

        <el-table-column prop="create_time" label="创建时间" width="180" :formatter="formatTime" />

        <el-table-column prop="functional" label="所属模块" width="180" show-overflow-tooltip />

        <el-table-column prop="execute_time" label="运行时间(s)" width="120" align="center" />

        <el-table-column prop="status" label="状态" width="120" align="center">
    <template #default="{ row }">
        <el-tag v-if="row.status === '1'" type="info">
            未执行
        </el-tag>
        <el-tag v-else-if="row.status === '2'" type="success">
            已执行
        </el-tag>
        <el-tag v-else type="warning">
            未知状态
        </el-tag>
    </template>
</el-table-column>

        <el-table-column label="下载" width="120" align="center">
            <template #default="{ row }">
                <el-button type="primary" size="small" @click="downloadCase(row)">
                    <el-icon>
                        <Download />
                    </el-icon>
                    下载
                </el-button>
            </template>
        </el-table-column>

        <el-table-column label="操作" align="center" fixed="right">
            <template #default="{ row }">
                <el-button type="success" size="small" @click="executeCase(row)" :disabled="isCaseExecuting || row.status === 1">
                    <el-icon v-if="isExecuting && row.id === currentExecutingCaseId">
                        <Loading />
                    </el-icon>
                    <el-icon v-else>
                        <Play />
                    </el-icon>
                    {{ isExecuting && row.id === currentExecutingCaseId ? '执行中...' : '立即执行' }}
                </el-button>
                <el-button type="danger" size="small" @click="deleteCase(row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[100, 200, 300, 400]"
        :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total=total @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { Download, Document, Loading, Play } from '@element-plus/icons-vue';

const uploadRef = ref(null);
const currentFile = ref(null);
const tableData = ref([]);
const currentPage4 = ref(1);
const pageSize4 = ref(5);
const total = ref('');
const dialogVisible = ref(false);
const isExecuting = ref(false); // 加载状态
const isCaseExecuting = ref(false); // 禁用状态
const currentExecutingCaseId = ref(null); // 当前执行的用例ID

const handleFileChange = (file) => {
    currentFile.value = file.raw;
};

const checkFile = (file) => {
    const isXlsx = file.type.includes('spreadsheetml') ||
        file.name.endsWith('.xlsx');
    if (!isXlsx) ElMessage.error('仅支持.xlsx格式');
    return isXlsx;
};

const case_name = ref('');
const functional = ref('');

const functional_options = [
    { value: '0', label: '模块1' },
    { value: '1', label: '模块2' },
    { value: '2', label: '模块3' }
];

const numberValidateForm = reactive({
    case_name: case_name,
    functional: functional
});

const formatTime = (row, column, cellValue) => {
    if (!cellValue) return '';
    const date = new Date(cellValue);
    return date.toLocaleString();
};

const submitUpload = async () => {
    if (!currentFile.value) return ElMessage.warning('请选择文件');
    if (!case_name.value) return ElMessage.warning('请输入用例名称');
    if (!functional.value) return ElMessage.warning('请选择所属模块');

    const formData = new FormData();
    formData.append('file', currentFile.value);
    formData.append('case_name', case_name.value);
    formData.append('functional', functional.value);
    dialogVisible.value = false;
    try {
        const res = await fetch('http://127.0.0.1:8000/uiautomation/ui', {
            method: 'POST',
            body: formData
        });
        const { code, data, message } = await res.json();

        if (code === 200) {
            ElMessage.success(message);
            getdata();
        } else {
            ElMessage.error(message || '上传失败');
        }
    } catch (err) {
        ElMessage.error(`请求异常: ${err.message}`);
    }
};

function executeCase(row) {
    // 加载状态
    isExecuting.value = true;
    // 禁用状态
    isCaseExecuting.value = true;
    // 当前执行的用例ID
    currentExecutingCaseId.value = row.id;
    axios.get('http://127.0.0.1:8000/uiautomation/execute', {
        params: {
            case_id: row.id
        }
    })
   .then(res => {
        if (res.data.status === 200) {
            ElMessage.success('用例执行成功，报告已生成');
            getdata();
        } else {
            ElMessage.error(res.data.message || '用例执行失败');
        }
        isExecuting.value = false;
        isCaseExecuting.value = false;
        currentExecutingCaseId.value = null;
    })
   .catch(err => {
        console.error(err);
        ElMessage.error('请求异常，请重试');
        isExecuting.value = false;
        isCaseExecuting.value = false;
        currentExecutingCaseId.value = null;
    });
}

function downloadCase(row) {
    axios.get('http://127.0.0.1:8000/uiautomation/download_case', {
        params: {
            case_id: row.id
        },
        responseType: 'blob'
    })
   .then(response => {
        // 生成文件名
        const contentDisposition = response.headers['content-disposition'];
        const fileName = contentDisposition ? contentDisposition.split('filename=')[1] : 'test_case.xlsx';

        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        ElMessage.success('下载成功');
    })
   .catch(error => {
        console.error('下载失败', error);
        ElMessage.error('下载失败，请重试');
    });
}

function deleteCase(row) {
    ElMessageBox.confirm(
        '确定要删除此测试用例吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
   .then(() => {
        axios.delete(`http://127.0.0.1:8000/uiautomation/delete_case/${row.id}/`)
       .then(res => {
            if (res.data.status === 200) {
                ElMessage.success('删除成功');
                getdata();
            } else {
                ElMessage.error(res.data.message || '删除失败');
            }
        })
       .catch(err => {
            console.error(err);
        });
    })
   .catch(() => {
        // 用户取消操作
    });
}

function getdata() {
    axios.get("http://127.0.0.1:8000/uiautomation/case_list", {
        params: {
            page: currentPage4.value,
            pagesize: pageSize4.value
        }
    })
   .then(res => {
        if (res.data.status === 200) {
            tableData.value = res.data.data || [];
            total.value = res.data.total || 0;
        } else {
            ElMessage.error(res.data.message || '获取数据失败');
        }
    })
   .catch(err => {
        console.error(err);
    });
}

function handleSizeChange(size) {
    pageSize4.value = size;
    getdata();
}

function handleCurrentChange(page) {
    currentPage4.value = page;
    getdata();
}

function handleRowClick(row) {
    // 可选：行点击事件处理
}

function handleClose(done) {
    // 可选：对话框关闭前的处理
    done();
}

function viewReport(row) {
    // 可选：查看报告功能
}

onMounted(() => {
    getdata();
});

// 在组件卸载前执行的操作
onUnmounted(() => {
    // 清理工作
});
</script>

<style scoped>
.el-table {
    --el-table-border-color: #ebeef5;
    --el-table-header-bg-color: #f5f7fa;
}

.el-table :deep(.el-table__cell) {
    padding: 8px 0;
}
</style>